package com.ee.chat.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.admin.service.ICreditExchangeService;
import com.ee.chat.admin.service.IOperationService;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.UserCoinLogMapper;
import com.ee.chat.common.dao.UserCreditExchangeLogMapper;
import com.ee.chat.common.dao.UserCreditLogMapper;
import com.ee.chat.common.dao.UserWalletMapper;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.service.IPushMessageService;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
public class CreditExchangeServiceImpl implements ICreditExchangeService {
    @Resource
    UserCreditExchangeLogMapper userCreditExchangeLogMapper;
    @Resource
    IOperationService operationService;
    @Resource
    UserWalletMapper userWalletMapper;
    @Resource
    UserCoinLogMapper userCoinLogMapper;
    @Resource
    UserCreditLogMapper userCreditLogMapper;
    @Resource
    IPushMessageService pushMessageService;

    @Override
    public Result list(HttpServletRequest request, Integer page, Integer limit, Integer userId, Integer status, String time) throws Exception {
        Map<String, Object> data = new HashMap<>();

        if(StringUtil.isEmpty(time) && userId == null && status == null){
            HttpSession session = request.getSession(true);
            List<String> userPermissions = (List<String>)session.getAttribute("userPermissions");
            if(!userPermissions.contains("/audit/creditExchange/viewList")){
                data.put("datas", new ArrayList<>());
                data.put("total", 0);

                return Result.returnSuccess(data);
            }
        }

        Date beginTime = null, endTime = null;
        if(!StringUtil.isEmpty(time)){
            String[] arr = time.split(" - ");
            beginTime = DateUtil.parse(arr[0]);
            endTime = DateUtil.parse(arr[1]);
        }

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userCreditExchangeLogMapper.list(p, userId, status, beginTime, endTime);
        List<Map<String, Object>> datas = iPage.getRecords();

        data.put("datas", datas);
        data.put("total", iPage.getTotal());

        operationService.addOperationLog(request, "查询积分兑换列表数据");

        return Result.returnSuccess(data);
    }

    @Override
    public Result audit(HttpServletRequest request, Integer id, Integer status, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserCreditExchangeLog userCreditExchangeLog = userCreditExchangeLogMapper.selectById(id);
        if(userCreditExchangeLog.getStatus() != 0){
            return Result.returnFailure("该记录已经审核，不能重复审核");
        }

        Map<String, String> push = new HashMap<>();

        UserWallet userWallet = userWalletMapper.getByUserId(userCreditExchangeLog.getUserId());
        if(status == 1) {    //通过
            //添加金币记录
            UserCoinLog userCoinLog = new UserCoinLog(userCreditExchangeLog.getUserId(), userCreditExchangeLog.getId(), 3, userCreditExchangeLog.getCoin(),
                    userCreditExchangeLog.getCredit()+"积分兑换"+userCreditExchangeLog.getCoin()+"金币");
            userCoinLogMapper.insert(userCoinLog);

            //更新用户钱包
            userWallet.setTotalCoin(userWallet.getTotalCoin() + userCreditExchangeLog.getCoin());
            userWallet.setActiveCoin(userWallet.getActiveCoin() + userCreditExchangeLog.getCoin());

            userCreditExchangeLog.setStatus(status);

            operationService.addOperationLog(request, "审核通过"+ userCreditExchangeLog.getUserId()+"用户积分兑换申请记录"+id);

            push.put("title", "积分兑换审核通过");
            push.put("content", "您提交的积分兑换审核已经通过，请注意查收");

        }else if(status == 2){  //拒绝
            //添加积分记录
            UserCreditLog userCreditLog = new UserCreditLog(userCreditExchangeLog.getUserId(), userCreditExchangeLog.getId(), 3, userCreditExchangeLog.getCredit()*1.0,
                    "驳回"+userCreditExchangeLog.getCredit()+"积分兑换"+userCreditExchangeLog.getCoin()+"金币");
            userCreditLogMapper.insert(userCreditLog);

            //更新用户钱包
            userWallet.setActiveCredit(userWallet.getActiveCredit() + userCreditExchangeLog.getCredit());

            userCreditExchangeLog.setReason(reason);
            userCreditExchangeLog.setStatus(status);

            operationService.addOperationLog(request, "审核拒绝"+ userCreditExchangeLog.getUserId()+"用户积分兑换申请记录"+id+"，原因："+reason);

            push.put("title", "积分兑换审核驳回");
            push.put("content", "您提交的积分兑换审核被驳回，原因：" + reason);
        }

        userWalletMapper.updateById(userWallet);

        //更新审核记录
        userCreditExchangeLog.setUpdateTime(new Date());
        userCreditExchangeLog.setAuditUserId(userId);
        userCreditExchangeLogMapper.updateById(userCreditExchangeLog);

        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userCreditExchangeLog.getUserId(), push);

        return Result.returnSuccess(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result cancelAudit(HttpServletRequest request, Integer id, String reason) throws Exception {
        HttpSession session = request.getSession(true);
        AdminUser adminUser = (AdminUser)session.getAttribute("adminUser");
        Integer userId = adminUser.getId();

        UserCreditExchangeLog userCreditExchangeLog = userCreditExchangeLogMapper.selectById(id);
        if(userCreditExchangeLog.getStatus() == 0){
            return Result.returnFailure("该记录未审核，无法撤销审核");
        }

        Map<String, String> push = new HashMap<>();

        /*UserWallet userWallet = userWalletMapper.getByUserId(userCreditExchangeLog.getUserId());
        if(userCreditExchangeLog.getStatus() == 1) {   //撤销通过审核
            //添加金币记录
            UserCoinLog userCoinLog = new UserCoinLog(userCreditExchangeLog.getUserId(), userCreditExchangeLog.getId(), 3, userCreditExchangeLog.getCoin(),
                    userCreditExchangeLog.getCredit()+"积分兑换"+userCreditExchangeLog.getCoin()+"金币");
            userCoinLogMapper.insert(userCoinLog);

            //更新用户钱包
            userWallet.setTotalCoin(userWallet.getTotalCoin() + userCreditExchangeLog.getCoin());
            userWallet.setActiveCoin(userWallet.getActiveCoin() + userCreditExchangeLog.getCoin());

            userCreditExchangeLog.setStatus(status);

            operationService.addOperationLog(request, "审核通过"+ userCreditExchangeLog.getUserId()+"用户积分兑换申请记录"+id);

            push.put("title", "积分兑换审核通过");
            push.put("content", "您提交的积分兑换审核已经通过，请注意查收");

        }else if(userCreditExchangeLog.getStatus() == 2){  //撤销拒绝审核
            //添加积分记录
            UserCreditLog userCreditLog = new UserCreditLog(userCreditExchangeLog.getUserId(), userCreditExchangeLog.getId(), 3, userCreditExchangeLog.getCredit()*1.0,
                    "驳回"+userCreditExchangeLog.getCredit()+"积分兑换"+userCreditExchangeLog.getCoin()+"金币");
            userCreditLogMapper.insert(userCreditLog);

            //更新用户钱包
            userWallet.setActiveCredit(userWallet.getActiveCredit() + userCreditExchangeLog.getCredit());

            userCreditExchangeLog.setReason(reason);
            userCreditExchangeLog.setStatus(status);

            operationService.addOperationLog(request, "审核拒绝"+ userCreditExchangeLog.getUserId()+"用户积分兑换申请记录"+id+"，原因："+reason);

            push.put("title", "积分兑换审核驳回");
            push.put("content", "您提交的积分兑换审核被驳回，原因：" + reason);
        }

        userWalletMapper.updateById(userWallet);

        //更新审核记录
        userCreditExchangeLog.setUpdateTime(new Date());
        userCreditExchangeLog.setAuditUserId(userId);
        userCreditExchangeLogMapper.updateById(userCreditExchangeLog);

        operationService.addOperationLog(request, "撤销审核"+ userCreditExchangeLog.getUserId()+"用户积分兑换申请记录"+id);

        //推送
        push.put("type", "1");
        pushMessageService.pushGeneralMessage(userCreditExchangeLog.getUserId(), push);*/

        return Result.returnSuccess(null);
    }
}
